﻿using AutoPrint.BJPT.Model;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using EXCEL = Microsoft.Office.Interop.Excel;

namespace AutoPrint.BJPT.Utils
{
    public class ComExcel
    {

        /// <summary>
        /// 打印完成事件
        /// </summary>
        public static event EventHandler Printed;
        /// <summary>
        /// 模板文件路径
        /// </summary>
        private readonly string TplPath = AppDomain.CurrentDomain.BaseDirectory + @"Libs\Tpl\" + ConfigurationManager.AppSettings["TplPath"];

        /// <summary>
        /// Excel保存路径
        /// </summary>
        private readonly string PrintPath =ConfigurationManager.AppSettings["PrintPath"]+'\\'+DateTime.Now.ToString("yyyy-MM-dd");


        /// <summary>
        /// EXCEL操作对象[非托管]
        /// </summary>
        EXCEL.Application App = new EXCEL.Application();
        /// <summary>
        /// WORKBOOK操作对象[非托管]
        /// </summary>
        EXCEL.Workbook WorkBook;
        /// <summary>
        /// WORKSHEET[非托管]
        /// </summary>
        EXCEL.Worksheet Sheet;

        /// <summary>
        /// 打印项数
        /// </summary>
        public int PrintCount =0;

        /// <summary>
        /// 打印二维码数组
        /// </summary>
        public string[] listEun;


        public ComExcel()
        {
            //路径判断
            if (!Directory.Exists(PrintPath))
            {
                Directory.CreateDirectory(PrintPath);
            }

            WorkBook = App.Workbooks.Add(TplPath);
            Sheet = new EXCEL.Worksheet();
            App.DisplayAlerts = false;
        }

        /// <summary>
        /// 打印
        /// </summary>
        /// <param name="models"></param>
        /// <param name="isPrint"></param>
        /// <param name="assetNum"></param>
        /// <returns></returns>
        public bool PrintData(List<EngineModel> models,bool isPrint,string assetNum)
        {
            try
            {
                if (models.Count == 0)
                {
                    MessageBox.Show("无打印内容,请稍后重试");
                    CloseExcel();
                    return false;
                }


                
                Sheet = WorkBook.Worksheets[1] as EXCEL.Worksheet;
                var usedRowsCount = Sheet.UsedRange.Rows.Count;
                //1.清空数据
                for (int i = 2; i <= usedRowsCount; i++)
                {
                    Sheet.Cells[i, 1] = "";
                    Sheet.Cells[i, 2] = "";
                    Sheet.Cells[i, 3] = "";
                    Sheet.Cells[i, 4] = "";
                }

                //2.填充数据
                for (int i = 0; i < models.Count; i++)
                {
                    var line = models[i];
                    Sheet.Cells[i + 2, 1] = (i + 1).ToString();
                    Sheet.Cells[i + 2, 2] = line.Eun;
                    Sheet.Cells[i + 2, 3] = line.Date + " " + line.Time;
                    Sheet.Cells[i + 2, 4] = assetNum;
                }

                //4.打印
                if (isPrint == true)
                {
                    //4.1打印格式整理
                    Sheet.UsedRange.Cells.Borders.LineStyle = 1;
                    Sheet.PageSetup.PrintArea = "A1:D" + (models.Count + 1).ToString();
                    Sheet.PageSetup.PaperSize = EXCEL.XlPaperSize.xlPaperB5;
                    Sheet.PageSetup.Zoom = false;
                    Sheet.PageSetup.TopMargin = 0.16;
                    Sheet.PageSetup.FitToPagesTall = false;
                    Sheet.PageSetup.FitToPagesWide = 1;
                    Sheet.PageSetup.PrintGridlines = true;
                    Sheet.PageSetup.CenterHorizontally = true;
                    //5.打印
                    //Sheet.PrintOutEx();

                    //6.触发打印完成事件
                    PrintCount = models.Count;
                    listEun = models.Select(item => item.Eun).ToArray();
                    Printed(this, new EventArgs());
                }

                //4.数据另存为
                var filePath = PrintPath + "\\" + DateTime.Now.ToString("HHmmssfff") + "-" + models[0].Eun + "";
                WorkBook.SaveAs(filePath, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value,
    EXCEL.XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value,
    Missing.Value, Missing.Value);


                CloseExcel();

                return true;
            }
            catch (Exception)
            {
                CloseExcel();
                throw;
            }
           
        }


        /// <summary>
        /// 关闭EXCEL
        /// </summary>
        public void CloseExcel()
        {
            WorkBook.Close(Missing.Value,Missing.Value,Missing.Value);
            App.Quit();
            try
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(Sheet);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(WorkBook);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(App);
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            finally
            {
                App = null;
                GC.Collect();
            }
        }

        
    }

}
